<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Station Device Application</title>
    <link href="/public/css/device.css?version=1" rel="stylesheet" type="text/css" />
    <link href="/public/lib/bootstrap/4.6.1/css/bootstrap.css" rel="stylesheet">
    <link href="/public/lib/adminlte/js/adminlte.min.js" rel="stylesheet" type="text/css" />
    <link href="/public/lib/adminlte/css/adminlte.min.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript" src="/ajax/libs/vue/2.7.10/vue.js"></script>
    <script src="/ajax/libs/axios/0.21.0/axios.min.js"></script>

    <script type="text/javascript" src="/ajax/libs/iview/3.5.0/iview.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/ajax/libs/iview/3.5.0/styles/iview.css">

    <link href="/public/lib/ionicons/3.0.0/css/ionicons.css" rel="stylesheet">
    <link href="/ajax/libs/font-awesome/5.15.4/css/all.css" rel="stylesheet">
</head>
<body>
<div id="app" class="app-container">
    <div class="kc-menu-fixed">
        <i-menu mode="horizontal" ref="menu" class="kc-menu"  :active-name="activeMenu">
            <menu-item v-for="menu in menus"  :key="menu.name"  :name="menu.name" :to="menu.url" >
                <i :class="menu.icon"></i>
                {{menu.title}}
            </menu-item>
        </i-menu>
    </div>
    <section class="content">
        <div class="container-fluid">
            <div class="card" style="margin-top: 0.5rem">
                <div class="card-header">
                    <h2 class="card-title"><i class="fas  fa-th-large"></i> {{ i18n["device.html.running_mode"]}}</h2>
                    <div class="card-tools">
                        <ul class="nav nav-pills ml-auto">
                            <li class="nav-item" @click="changeMode(false)">
                                <a class="nav-link" :class="{'active': !(debugMode) }" data-toggle="tab"
                                   >{{ i18n["device.html.simulator"]}}</a>
                            </li>
                            <li class="nav-item" @click="changeMode(true)">
                                <a class="nav-link" :class="{'active': (debugMode) }" data-toggle="tab"
                                   >{{ i18n["device.html.debug"]}}</a>
                            </li>
                        </ul>
                    </div>
                </div>
                <!-- /.card-header -->
                <!-- form start -->

                <div class="card-body" v-show="(!debugMode)">
                    <div class="wrap-text">
                        {{ i18n["device.html.wall_ptl_tips1"]}}
                        <br/>
                        {{ i18n["device.html.wall_ptl_tips2"]}}
                    </div>
                </div>
                <div class="card-body" v-show="(debugMode)">
                    <div class="wrap-text">
                        {{ i18n["device.html.wall_ptl_tips1"]}}
                        <br/>
                        {{ i18n["device.html.wall_ptl_tips2"]}}
                    </div>
                </div>
            </div>
            <!-- /.card-body -->
            <!-- Horizontal Form -->
            <div class="callout callout-danger" v-show="!(lightType==='ptl')">
                <h6>{{ i18n["device.html.station_cs_light_type"]}}：{{lightType}} </h6>
                <br/>
                <h6>{{ i18n["device.html.station_cs_to_strip"]}}</h6>
            </div>
            <div class="row" v-show="lightType==='ptl'" style="margin-left: 0; margin-right: 0;" >
                <div class="card col-6" <#--style="margin-top: 0.5rem"--> v-for="point in this.layouts">
                    <div class="card-header">
                        <h2 class="card-title"><i class="fas fa-ruler-vertical"></i> {{ i18n["device.html.point"]}} : {{point.pointCode}}</h2>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <div class="row">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-3" style="margin-top: 1rem" v-for="light in point.lights">
                                    <div class="row">
                                        <div class="col-12" style="display: flex;justify-content: center">
                                            <a class="btn btn-app"
                                               :class="{'bg-warning': (getLightStateByNo(light.lightNo).lightStatus==='LIGHT_ON') }"
                                               @click="press(light.lightNo)"
                                               style="height: 80px;border-radius: 50px;margin: 0">
                                                <span class="badge bg-danger" style="font-size: 14px;"
                                                      v-show="getLightStateByNo(light.lightNo).ledStatus==='LED_ON'">{{getLightStateByNo(light.lightNo).num}}</span>
                                                <i class="fas fa-lightbulb"></i>
                                                <span style="font-size: 18px;">{{light.lightNo}}</span>
                                            </a>
                                        </div>
                                        <div class="col-12">
                                            <span style="display: block; text-align: center;">{{light.lightIndex}}</span>
                                        </div>
                                    </div>

                                </div>

                            </div>

                        </div>
                    </div>
                    <!-- /.card-body -->
                </div>
            </div>
        </div>
    </section>
</div>

<script>
    var app = new Vue({
        el: '#app',
        data() {
            return {
                i18n: {},
                activeMenu:'container_ptl',
                menus:[{
                    name:'index',
                    url:'/admin/device/index',
                    icon:'fas fa-warehouse',
                    title:'系统信息'
                },{
                    name:'config',
                    url:'/admin/device/config',
                    icon:'fas fa-cogs',
                    title:'设置'
                }],
                deviceUrl: "http://localhost:8888/station/device/code",
                deviceCode: "1231232",
                stationCode: "",
                localIP: "127.0.0.1",
                hostIP: "127.0.0.1",
                visible: false,
                debugMode: true,
                lightType: "ptl",
                layouts: [],
                states: [
                    {
                        "lightNo": 11,
                        "lightStatus": "LIGHT_ON",
                        "color": "RED",
                        "ledStatus": "LED_ON",
                        "num": 70,
                        "buttonStatus": "BEEP_UNLOCK",
                        "beepStatus": "BEEP_OFF"
                    },
                    {
                        "lightNo": 12,
                        "lightStatus": "LIGHT_OFF",
                        "color": "RED",
                        "ledStatus": "LED_OFF",
                        "num": 0,
                        "buttonStatus": "BEEP_UNLOCK",
                        "beepStatus": "BEEP_OFF"
                    },
                    {
                        "lightNo": 13,
                        "lightStatus": "LIGHT_ON",
                        "color": "RED",
                        "ledStatus": "LED_ON",
                        "num": 50,
                        "buttonStatus": "BEEP_UNLOCK",
                        "beepStatus": "BEEP_OFF"
                    }
                ]
            }
        },
        mounted() {
            window.app = this;
            // 界面初始化信息
            this.getI18NResource();
            this.getMenus(this.activeMenu);
            // 界面数据初始化
            this.init();
        },
        computed: {
            getLightStateByNo() {
                // 返回一个函数，接收 userId 作为参数
                return (lightNo) => {
                    let lightState = this.states.find(item => item.lightNo === lightNo);
                    if (!lightState) {
                        lightState = {
                            "lightNo": lightNo,
                            "lightStatus": "LIGHT_OFF",
                            "color": "RED",
                            "ledStatus": "LED_OFF",
                            "num": 0,
                            "buttonStatus": "BEEP_UNLOCK",
                            "beepStatus": "BEEP_OFF"
                        }
                    }
                    return lightState;
                };
            }
        },
        methods: {
            init() {
                // 加载系统配置信息
                this.getDeviceProperties();
                // 获取灯光布局信息
                this.fetchData();
            },
            getI18NResource() {
                axios.get('/admin/i18n/mappings/default')
                    .then(response => {
                        let result = response.data
                        this.i18n = result.data;
                    })
                    .catch(error => {
                        this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                    });
            },
            getMenus(activeMenu){
                axios.get('/admin/device/menus')
                    .then(response => {
                        if(!response.data.success){throw response.data.message;}
                        let result = response.data
                        this.menus = result.data;
                        this.$nextTick(() => {
                            this.$refs.menu.updateActiveName(activeMenu);
                        });
                    })
                    .catch(error => {
                        this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                    });
            },
            reload() {
                window.location.reload();
            },
            refreshData() {
                // 获取界面数据
                console.log("start refresh data")
                this.getLightState();
            },
            fetchData() {
                // 获取服务器工作站编码
                axios.get('/station/device/stationCode')
                    .then(response => {
                        let result = response.data
                        let stationCode = result.data;

                        // 通过 stationCode 执行后续逻辑
                        if (!stationCode) {
                            this.$Message.error(this.i18n["device.error.STATION_NOT_BIND"]);
                        }

                        // 监听服务器变更
                        this.listenServer(stationCode);

                        // 获取灯光布局
                        this.getLayout(stationCode);

                        // 获取运行模式
                        axios.get('/admin/device/container-ptl/getMode')
                            .then(response => {
                                let result = response.data
                                this.debugMode = result.data;
                                // 获取灯光数据
                                this.getLightState();
                            })
                            .catch(error => {
                                this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                            });
                    })
                    .catch(error => {
                        this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                    });
            },
            getDeviceProperties() {
                axios.get('/station/device/properties/get')
                    .then(response => {
                        let result = response.data
                        this.properties = result.data;
                    })
                    .catch(error => {
                        this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                    });
            },
            getStationCode() {
                axios.get('/station/device/stationCode')
                    .then(response => {
                        let result = response.data
                        if (result.data) {
                            this.stationCode = result.data;
                        }
                        if (this.stationCode === null || this.stationCode === undefined || this.stationCode === "") {
                            this.stationCode = this.i18n["device.html.not_bind"]
                        }
                        return this.stationCode;
                    })
                    .catch(error => {
                        this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                    });
            },
            getLayout(stationCode) {
                let url = '/admin/device/container-ptl/layouts?stationCode='+stationCode;
                axios.get(url)
                    .then(response => {
                        let result = response.data
                        if(!result.success){throw result.message;}
                        this.layouts = result.data.layouts;
                        this.lightType = result.data.lightType;
                    })
                    .catch(error => {
                        this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                    });
            },
            getMode() {
                axios.get('/admin/device/container-ptl/getMode')
                    .then(response => {
                        let result = response.data
                        this.debugMode = result.data;
                    })
                    .catch(error => {
                        this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                    });
            },
            changeMode(debugMode) {
                let url = '/admin/device/container-ptl/setMode?inDebugMode='+debugMode;
                axios.get(url)
                .then(response => {
                    let result = response.data
                    this.debugMode = result.data;
                })
                .catch(error => {
                    this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                });
                // 模式调整后刷新灯光数据
                this.debugMode = debugMode;
                this.refreshData();
            },
            getLightState() {
                // 提取所有的灯号信息
                let lightNos = [];
                for (let item of this.layouts) {
                    for (let subItem of item.lights) {
                        lightNos.push(subItem.lightNo);
                    }
                }
                console.log(" lightNos ", JSON.stringify(lightNos))
                axios.post('/admin/device/container-ptl/states', {
                    debug: this.debugMode,
                    lightNos: lightNos
                })
                    .then(response => {
                        let result = response.data
                        this.states = result.data;
                    })
                    .catch(error => {
                        this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                    });
            },
            listenServer(stationCode) {
                // 检查原生支持
                /*if (typeof EventSource === 'undefined') {
                    window.EventSource = window.EventSourcePolyfill;
                }*/

                // 现在可以正常使用 EventSource
                let url = '/station/refresh/sse?stationCode=' + stationCode;
                let eventSource = new EventSource(url);
                eventSource.onmessage = (event) => {
                    console.log('SSE 数据:', event.data);
                    this.refreshData();
                };
                eventSource.onerror = (error) => {
                    console.error('连接错误:', error);
                    // 自定义重连逻辑
                    if (eventSource.readyState === EventSource.CLOSED) {
                        console.log('尝试在 3 秒后重连...');
                        setTimeout(connect, 3000);
                    }
                };
            },
            createWebSocketSse(stationCode) {
                let socket = new WebSocket(url.replace('http', 'ws'));

                socket.onopen = function () {
                    console.log('WebSocket 连接已建立');
                };

                socket.onmessage = function (event) {
                    console.log('收到消息:', event.data);
                    // 处理数据，模拟 SSE 事件
                    let data = JSON.parse(event.data);
                    // 根据数据类型分发事件
                };

                socket.onerror = function (error) {
                    console.error('WebSocket 错误:', error);
                };

                socket.onclose = function (event) {
                    console.log('WebSocket 连接已关闭，尝试重连...');
                    setTimeout(() => createWebSocketSse(url), 3000);
                };

                return {
                    close: () => socket.close()
                };
            },
            press(lightNo) {
                let url = '/admin/device/container-ptl/press?inDebugMode='+this.debugMode+'&lightNo='+lightNo;
                axios.get(url)
                .then(response => {
                    let result = response.data;
                    if(!result.success){
                        throw result.message;
                    }
                    this.$Message.success(this.i18n["device.error.SUCCESS"]);
                })
                .catch(error => {
                    this.$Message.error({content: this.i18n["device.error.FAIL"]+":"+error, duration: 3, closable: true});
                });
            }

        }
    });
    //app.use(ViewUIPlus);
    //app.mount("#app");
    function refreshData() {
        window.app.refreshData();
    }
</script>
</body>
</html>